package com.example.health.controller;


import com.example.health.common.Result;
import com.example.health.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传oss
 */
@Slf4j
@RestController
@RequestMapping("/files")
public class UploadController {
    /**
     * 本地磁盘存储方法
     * @param name
     * @param age
     * @param file
     * @return
     * @throws IOException

    @PostMapping("/upload")
    public Result upload(String name, Integer age, MultipartFile file) throws IOException {
        log.info("接收参数:{},{},{}",name,age,file);
        //获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//        file.transferTo(new File("F:/upload/"+originalFilename));
        String path = this.getClass().getResource("/").getPath();
        String targetDir=path+"upload/";
        File dir=new File(targetDir);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String str = UUID.randomUUID().toString();
        str+=extension;
        targetDir+=str;
        log.info("target{}",targetDir.toString());
        file.transferTo(new File(targetDir));
        return  Result.success();
    } //本地磁盘存储方法
     */
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @PostMapping("/upload")
    public Result upload(MultipartFile  file) throws Exception {
        log.info("文件上传{}",file.getOriginalFilename());
        //将文件交给oss存储管理
        String url= aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传oss,url:{}",url);
        return  Result.success(url);

    }

}
